package com.lhy.admin.service;

import com.lhy.admin.common.mvcplus.service.SimpleService;
import com.lhy.admin.mapper.DepartmentMapper;
import com.lhy.admin.model.Department;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class DepartmentService extends SimpleService<DepartmentMapper, Department> {

    /**
     * @param id
     * @return int
     * @throws
     * @Title: delPermission
     * @Description: 根据部门id 删除部门和子部门
     * @date 2018/6/11 17:14
     */
    @Transactional(rollbackFor = Exception.class)
    public int delDepartment(Integer id) {
        //删除自己
        this.removeById(id);
        //删除子权限
        this.remove(new Department().setParent(id));
        return 1;
    }

    public boolean createDepartment(Department bean) {
        Integer level = Optional.ofNullable(bean.getParent())
                .map(this::getById)
                .map(Department::getLevel)
                .map(integer -> integer + 1).orElse(1);
        Department department = bean.setLevel(level);
        this.save(department);
        Department department1 = new Department().setId(department.getId()).setAncestors(department.getAncestors() + department.getId());
        return this.updateSelectiveById(department1);
    }

}
